import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const isLoggedIn = ref(false)
  const userPhone = ref('')
  const token = ref('')

  // 初始化登录状态
  const init = () => {
    const storedToken = localStorage.getItem('token')
    const storedPhone = localStorage.getItem('userPhone')
    if (storedToken) {
      token.value = storedToken
      isLoggedIn.value = true
      userPhone.value = storedPhone || ''
    }
  }

  // 登录方法
  const login = (phone, newToken) => {
    isLoggedIn.value = true
    userPhone.value = phone
    token.value = newToken
    localStorage.setItem('token', newToken)
    localStorage.setItem('userPhone', phone)
  }

  // 退出方法
  const logout = () => {
    isLoggedIn.value = false
    userPhone.value = ''
    token.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('userPhone')
  }

  // 立即初始化
  init()

  return { isLoggedIn, userPhone, token, login, logout, init }
})
